import datetime

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import  redirect
from django.conf import settings

from app01 import models

class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None

class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):

        # 0.排除那些不需要登录就能访问的页面
        # request.path_info 获取当前用户请求的URL
        exclude_url = settings.WHITE_LIST_URL 
        if request.path_info in exclude_url:
            return

        # 1.读取当前访问的用户的session信息，如果能读到，说明已登陆过，就可以继续向后走。
        info_dict = request.session.get("info")
        # print(info_dict)

        if info_dict:
            # 登录成功, 访问管理系统: 获取当前用户额度
            # 创建对象
            request.tracer = Tracer()
            # 方式一: 免费额度在交易记录中存储
            # 获取当前用户id值最大 (最近交易记录)
            user_object = models.User.objects.filter(id=info_dict['id']).first()
            # print(user_object)

            # 赋user对象
            request.tracer.user = user_object
            
            _object = models.Transaction.objects.filter(user=user_object,status=1).order_by('-id').first()
            # print(_object)

            # 判断是否已经过期, 过期回到免费版
            current_datetime = datetime.datetime.now()
            if _object.end_datetime and _object.end_datetime.replace(tzinfo=None) < current_datetime:
                _object = models.Transaction.objects.filter(user=user_object,status=1,price_policy__category=1).first()
            
            # 赋price_policy对象
            request.tracer.price_policy = _object.price_policy
           

            # 方式二: 免费的额度存储配置文件
            """ # 获取当前用户id值最大 (最近交易记录)
            user_object = models.User.objects.filter(id=info_dict['id']).first()
            _object = models.Transaction.objects.filter(user=user_object,status=1).order_by('-id').first()
            if not _object:
                # 没有购买 - 免费版
                request.price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
            else:
                # 付费版
                # 判断是否已经过期, 过期回到免费版
                current_datetime = datetime.datetime.now()
                if _object.end_datetime < current_datetime and _object.end_datetime:
                    request.price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
                else:
                    request.price_policy = _object.price_policy """

            
            return

        # 2.没有登录过，重新回到登录页面
        return redirect('/login/')

    def process_view(self, request, view, args, kwargs):
        
        # 1. 判断URL是否以manage开头
        if not request.path_info.startswith('/manage/'):
            return


        # 2. project_id 是我创建 or 我参与的项目
        # 我创建的
        user = request.tracer.user
        project_id = kwargs.get('project_id')
        project_object = models.Project.objects.filter(creator=user, id=project_id).first()

        if project_object:
            # 说明是我创建的项目
            request.tracer.project = project_object
            return
        
        # 我参与的
        project_user_object = models.ProjectUser.objects.filter(join_user=user, project_id=project_id).first()
        if project_user_object:
            # 说明是我参与的项目
            request.tracer.project = project_user_object.project
            return
        
        return redirect('/project/list/')

        
